﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace MyPhotoIndex.Settings
{
    [Serializable]
    public class RecentlyUsedIndexList : List<PhotoIndexInfo>
    {
        private readonly int LengthOfRecentList = 5;

        public void UpdateIndexInfo(string indexId, string path, string indexName, int indexImageCount)
        {
            foreach (PhotoIndexInfo pii in this)
            {
                if (path.CompareTo(pii.Path) == 0)
                {
                    if (pii.Name.CompareTo(indexName) == 0 &&
                        pii.ImageCount == indexImageCount &&
                        pii.Id == indexId)
                    {
                        return;
                    }
                    else
                    {
                        pii.Id = indexId;
                        pii.ImageCount = indexImageCount;
                        pii.Name = indexName;
                        pii.Path = path;
                        ApplicationSettings.Default.Save();
                        return;
                    }
                }
            }

            //this is a new index;

            PhotoIndexInfo photoIndexInfo = new PhotoIndexInfo();
            photoIndexInfo.Name = indexName;
            photoIndexInfo.Id = indexId;
            photoIndexInfo.ImageCount = indexImageCount;
            photoIndexInfo.Path = path;

            if (this.Count >= LengthOfRecentList)
            {
                this.RemoveAt(this.Count - 1);
            }

            for (int i = this.Count - 1; i >= 0; i--)
            {
                if (File.Exists(this[i].Path) == false)
                {
                    this.RemoveAt(i);
                }
            }

            this.Insert(0, photoIndexInfo);

            ApplicationSettings.Default.Save();
        }
    }
}
